import { createStore } from 'vuex'
//数据管理框架
//创建了一个全局唯一的框架，用来存放全局的数据
const user = {
  state: () => ({
    age: 18,
    slogen: 'a'
  }),
  getters: {
    fullName(state) {
      return state.age + state.slogen
    },
    fullName2(state, getters) {
      return getters.fullName + state.slogen
    },
    fullName3(state, getters, rootState) {
      return getters.fullName + rootState.name
    }

  },
  mutations: {
    setSlogen(state, payload) {
      state.slogen = payload;
    }
  },
  //context={commit,state,getters,rootState,rootGetters}
  actions: {
    text({ commit }, payload) {
      setTimeout(() => {
        commit('setSlogen', payload)
      }, 2000)

    }
  }
}
export default createStore({
  state: {
    name: 'lee',
    cartList: [{ name: 'a', price: 1 }, { name: 'a', price: 2 }, { name: 'a', price: 3 }]
  },
  //mutation里面不能有异步代码
  getters: {
    goodsFilter(state) {
      return state.cartList.filter(v => v.price > 0)
    },
    totalPrice(state, getters) {
      return getters.goodsFilter.reduce((s, v) => s + v.price, 0)
    },
    goodsSelf(state) {
      return function (price) {
        return state.cartList.filter(v => v.price > price)
      }
    }

  },
  mutations: {
    //4.对应的mutation执行
    change(state, str) {
      state.name = str
    },
    changeName(state, str) {
      state.name = str
    },
    setSlogen(state, payload) {
      state.name = payload;
    }

  },
  actions: {
    //2.store感知到你触发一个叫change的action。执行change方法
    //content={commit,state,getters}
    change({ commit }, str) {
      //3.提交一个commit触发一个mutation
      setTimeout(() => {
        commit('change', str)
      }, 2000)
    },
    changeName(context, str) {
      setTimeout(() => {
        context.commit('changeName', str)
      }, 1000)
    }
  },
  modules: {
    user
  }
})
